package db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


public class DbConnection {
    private static final String USER = "root";
    private static final String PASSWORD = "123456";
    private static final String URL = "jdbc:mysql://localhost:3306/library?characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8";
    private static Connection conn;

    /**
     * 获得一个数据库连接对象
     *
     * @return java.sql.Connection实例
     */
    public static Connection getConnection() {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver"); // mysql8注册驱动，不建议省略
            if (conn == null || conn.isClosed()) { // 部分同学出现No operations allowed after connection
                // closed，具体原因未明确，此处可加isClosed进行判断有助排除。
                conn = DriverManager.getConnection(URL, USER, PASSWORD);
            } else {
                return conn;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return conn;
    }

    /**
     * 释放数据库资源
     */
    public static void close(PreparedStatement ps, ResultSet rs,Connection conn) {
        try {
            if (rs != null) {
                rs.close();
                rs = null;
            }
            if (ps != null) {
                ps.close();
                ps = null;
            }
            if (conn != null) {
                conn.close();
                conn = null; // 部分同学出现No operations allowed after connection closed，具体原因未明确。此处可加conn
                // =null有助于排除。
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
